package org.scratchcrew.web.cometd;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.server.BayeuxService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class extends BayeuxService and delegates message handling to an
 * external object. To initialize object from this class you should provide
 * {@link BayeuxMessageHandler}
 */
public class SpringBayeuxService extends BayeuxService {
	private static final String HANDLER_METHOD_NAME = "handleMessage";

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private BayeuxMessageHandler messageHandler;

	public SpringBayeuxService(Bayeux bayeux, String name, int maxThreads) {
		super(bayeux, name, maxThreads);
	}

	public SpringBayeuxService(Bayeux bayeux, String name) {
		super(bayeux, name);
	}

	public void setMessageHandler(BayeuxMessageHandler messageHandler) {
		this.messageHandler = messageHandler;
	}

	/**
	 * Initializing method. Gets the channel id from the
	 * {@link BayeuxMessageHandler} and subscribes this service to the channel.
	 */
	public void init() {
		String channelId = this.messageHandler.getChannelId();
		// Subscribe handler to channel
		subscribe(channelId, HANDLER_METHOD_NAME);
	}

	public final Object handleMessage(Client fromClient, String channel,
			Object data, String id) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Handling from client %s "
					+ "on channel %s. data is %s. id is %s", fromClient,
					channel, data, id));
		}
		Object reply = this.messageHandler
				.handle(fromClient, channel, data, id);
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Replying %s ", reply));
		}
		return reply;
	}

}
